package com.sylingd.blog.activity

import android.app.Activity
import android.content.Intent
import android.graphics.Bitmap
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.Toolbar
import android.util.Log
import android.view.Menu
import android.view.View
import android.webkit.WebView
import android.widget.FrameLayout
import android.widget.ProgressBar
import android.widget.Toast
import com.google.gson.Gson
import com.google.gson.JsonElement
import com.sylingd.blog.BaseApplication
import com.sylingd.blog.R
import com.sylingd.blog.bean.Article
import com.sylingd.blog.lib.Api
import com.sylingd.blog.lib.Config
import com.sylingd.blog.lib.Setting
import com.sylingd.blog.lib.WebViewBridge
import com.sylingd.blog.ui.adapter.ArticleAdapter

class ReadActivity : AppCompatActivity() {

	private var id: Int = 0
	private lateinit var mArticle: Article
	private lateinit var mWebView: WebView
	private lateinit var mWebContainer: FrameLayout

	companion object {
		fun launch(context: Activity, id: Int, title: String) {
			val intent = Intent(context, ReadActivity::class.java)
			intent.putExtra("id", id)
			intent.putExtra("title", title)
			context.startActivity(intent)
		}
		fun launch(context: Activity, id: Int) = launch(context, id, "")
	}

	override fun onCreate(savedInstanceState: Bundle?) {
		super.onCreate(savedInstanceState)

		setContentView(R.layout.activity_read)
		val toolbar = findViewById<Toolbar>(R.id.toolbar)
		setSupportActionBar(toolbar)

		title = intent.getStringExtra("title")
		id = intent.getIntExtra("id", -1)

		supportActionBar?.setDisplayHomeAsUpEnabled(true)
		toolbar.setNavigationOnClickListener({
			finish()
		})

		BaseApplication.initSlidr(this)

		//初始化mArticle
		mArticle = Article(-1, "", "", "", "")

		//右上角菜单点击事件
		toolbar.setOnMenuItemClickListener {
			when (it.itemId) {
				R.id.share -> {
					//分享链接
					if (mArticle.id != -1) {
						val textIntent = Intent(Intent.ACTION_SEND);
						textIntent.type = "text/plain";
						textIntent.putExtra(Intent.EXTRA_TEXT, mArticle.getURL())
						startActivity(Intent.createChooser(textIntent, getString(R.string.share)))
					}
				}
				R.id.copy_link -> {
					//复制链接
					if (mArticle.id != -1) {
						(getSystemService(android.content.Context.CLIPBOARD_SERVICE) as android.content.ClipboardManager)
								.primaryClip = android.content.ClipData.newPlainText("Label", mArticle.getURL())
					}
				}
			}
			true
		}

		//创建WebView
		mWebContainer = findViewById(R.id.content)
		mWebView = WebView(applicationContext)
		val loading = findViewById<ProgressBar>(R.id.contentLoading)
		WebViewBridge(this, mWebView, object: WebViewBridge.Client() {
			override fun onPageStarted(view: WebView?, url: String?, favicon: Bitmap?) {
				super.onPageStarted(view, url, favicon)
				//两秒钟后即使没有渲染完成，也进行显示
				Thread({
					Thread.sleep(2000)
					mWebContainer.post({
						loading.visibility = View.GONE
						mWebView.visibility = View.VISIBLE
					})
				}).start()
			}
			override fun onPageFinished(view: WebView?, url: String?) {
				super.onPageFinished(view, url)
				mWebContainer.post({
					loading.visibility = View.GONE
					mWebView.visibility = View.VISIBLE
				})
			}
		})

		load()
	}

	//创建菜单
	override fun onCreateOptionsMenu(menu: Menu?): Boolean {
		menuInflater.inflate(R.menu.activity_read_menu, menu)
		return true
	}

	override fun onPause() {
		super.onPause()
		mWebView.onPause()
		mWebView.pauseTimers()
	}

	override fun onResume() {
		super.onResume()
		mWebView.resumeTimers()
		mWebView.onResume()
	}

	override fun onDestroy() {
		mWebContainer.removeAllViews()
		mWebView.stopLoading()
		mWebView.removeAllViews()
		mWebView.destroy()
		super.onDestroy()
	}

	//加载内容
	private fun load() {
		//创建webview
		val webviewLayout = FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.WRAP_CONTENT)
		mWebView.visibility = View.GONE
		mWebView.setBackgroundColor(0)
		mWebView.layoutParams = webviewLayout
		mWebContainer.addView(mWebView)
		val req = Api.ApiRequest("article/get")
		req.param.put("id", id)
		Api.call(req, object: Api.Callback() {
			override fun onFail(message: String?) {
				super.onFail(message)
				if (message != null) {
					mWebContainer.post({
						Toast.makeText(this@ReadActivity, message, Toast.LENGTH_SHORT).show()
					})
				} else {
					mWebContainer.post({
						Toast.makeText(this@ReadActivity,  getString(R.string.load_fail_message), Toast.LENGTH_SHORT).show()
					})
				}
				this@ReadActivity.finish()
			}
			override fun onSuccess(data: JsonElement) {
				val gsonObj = Gson()
				mArticle = gsonObj.fromJson(data, Article::class.java)
				val html = getHtml(mArticle)
				mWebContainer.post({
					title = mArticle.title
					mWebView.loadDataWithBaseURL(Config.baseUrl, html, "text/html; charset=utf-8", "utf-8", null)
				})
			}
		})
	}

	//适配HTML
	private fun getHtml(article: Article): String {
		val tags = article.tags
		//标题
		val title = article.title
		//移除所有的style等标签
		var trimedHtml = Regex("""style="(.*?)"""").replace(article.body, "")
		trimedHtml = Regex("""<font(.*?)>(.*?)</font>""").replace(trimedHtml, "$2")
		//读取设置中的字号
		val fontSize = Setting.get(Setting.NAME_CONTENT_TEXT_SIZE, Setting.DEFAULT_CONTENT_TEXT_SIZE)
		return """<head>
			<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
			<meta charset="utf-8">
			<link rel="stylesheet" type="text/css" href="https://android_assets/read.css">
			<script>var fontSize=$fontSize;var tags="$tags";</script>
		</head>
		<body>
			<div class="title">$title</div>
			<div class="tags"></div>
			<div class="content">$trimedHtml</div>
			<script src="https://android_assets/read.js"></script>
		</body>"""
	}
}
